package org.ghost.springboot2.demo.service.impl;

import org.ghost.springboot2.demo.service.IDemoService;
import org.ghost.springboot2.demo.service.ITestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;

@Service
public class TestServiceImpl implements ITestService {
    private final static Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private IDemoService demoService;

    @Override
    public Map<String, Object> getUserInfo(Long id) {
        String sql = "SELECT * FROM t_user WHERE id = :id";
        return jdbcTemplate.queryForMap(sql, new MapSqlParameterSource("id", id));
    }

    @Override
    public int updateNameById(String name, Long id) {
        String sql = "UPDATE t_user SET user_name = :name WHERE id = :id";
        return jdbcTemplate.update(sql, new MapSqlParameterSource("id", id).addValue("name", name));
    }

    /**
     * 这里要注意一下this.demoService.getUserInfo(id)执行完会调用DbContext.remove()
     * 导致后续流程可能会出现问题
     *
     * @param name
     * @param age
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int updateInfoById(String name, Integer age, Long id) {
        Map<String, Object> data = this.demoService.getUserInfo(id);
        if (data != null && !Objects.equals(data.get("name"), name)) {
            String sql = "UPDATE t_user SET user_name = :name,age =:age WHERE id = :id";
            return jdbcTemplate.update(sql, new MapSqlParameterSource("id", id).addValue("name", name).addValue("age", age));
        }
        return 0;
    }
}
